/*
 * Copyright (C) 2010,2011.
 * AHCP Project
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 *     http://www.apache.org/licenses/LICENSE-2.0 
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 
 * express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package org.jacp.demo.service;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.jacp.api.action.IAction;
import org.jacp.api.action.IActionListener;
import org.jacp.demo.util.DropShadowPanel;
import org.jacp.swing.rcp.component.AStatelessComponent;

/**
 * Handles erros while image loading, decide if retry loading or skip image
 * @author Andy Moncsek
 *
 */
public class ErrorService extends AStatelessComponent {
    private static final int MAX_RETRY=5;
    private static final ConcurrentHashMap<String, Integer> errorCounter = new ConcurrentHashMap<String, Integer>();

    @Override
    public Object handleAction(IAction<ActionEvent, Object> action) {
    	
    	  
	final Object message = action.getLastMessage();
	if(message instanceof org.jacp.demo.util.DropShadowPanel) {
	    final DropShadowPanel panel = (DropShadowPanel) message;
	    Integer count = 0;
	    if(errorCounter.containsKey(panel.getFilePath())) {
		count = errorCounter.get(panel.getFilePath())==null?1:errorCounter.get(panel.getFilePath());
		errorCounter.remove(panel.getFilePath());
		if(count >=MAX_RETRY) {	    
		    return null;

		} 
	    } 		    
	    errorCounter.put(panel.getFilePath(), count+1);
	    retry(panel);
	}
	return null;
    }
    
    private final void retry(final DropShadowPanel panel) {
	List<DropShadowPanel> errors = new ArrayList<DropShadowPanel>();
	errors.add(panel);
	final IActionListener<ActionListener, ActionEvent, Object> listener = getActionListener();
	listener.getAction().addMessage("id01.id06",errors);
	listener.getListener().actionPerformed(
		listener.getAction().getActionEvent());
    }

}
